<template>
  <div>
    <h2>动态组件</h2>
    <div class="dynamic">
      <div class="dynamic-ctrl">
        <div class="ctrl-item" v-for="(value, key) in dynamicComponents" :key="key" @click="setComponentName(key)">{{ key }}</div>
      </div>
      <div class="dynamic-panel">
        <keep-alive>
          <component :is="componentName" />
        </keep-alive>
      </div>
    </div>

    <h2>异步组件</h2>
    <div class="dynamic">
      <div class="dynamic-ctrl">
        <div class="ctrl-item" @click="setAsyncComponentName">切换</div>
      </div>
      <div class="dynamic-panel">
        <component :is="asyncComponentName" />
      </div>
    </div>

  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import {
  components as dynamicComponents,
  componentNames,
} from './components/Dynamic'
import AsyncComponent from './components/Async'

@Component({
  name: 'DynamicAndAsync',
  components: {
    ...dynamicComponents,
    'AsyncComponent': AsyncComponent,
    // AsyncComponent: () => import('./components/Async/AsyncComponent.vue'),
  },

})
export default class extends Vue {
  private dynamicComponents = dynamicComponents

  private componentName = componentNames.length > 0 ? componentNames[0] : ''

  setComponentName(name: string) {
    name && (this.componentName = name)
  }

  private asyncComponentName = ''

  setAsyncComponentName() {
    this.asyncComponentName = !this.asyncComponentName ? 'asyncComponent' : ''
  }
}
</script>

<style lang="scss">
.dynamic {
  .dynamic-ctrl {
    font-size: 0;
    letter-spacing: 0;
    .ctrl-item {
      display: inline-block;
      border: 1px solid #ccc;
      border-bottom: 0;
      border-radius: 5px 5px 0 0;
      font-size: 14px;
      padding: 5px 10px;
      cursor: pointer;

      &:nth-child(2n + 1) {
        background-color: #e0e0e0;
      }

      &:nth-child(2n) {
        background-color: #f0f0f0;
      }

      &:hover, &.active {
        background-color: #e0e0e0;
      }
    }
  }

  .dynamic-panel {
    border: 1px solid #ccc;
    padding: 10px;
  }
}
</style>
